package zing.downloader;

import org.jsoup.nodes.Element;
import zing.downloader.controller.HtmlController;
import zing.downloader.entity.Song;
import zing.downloader.executor.DownloadExecutor;
import zing.downloader.interfaces.IDownloadExecutor;
import zing.downloader.interfaces.IHtmlController;
import zing.downloader.interfaces.IZingDownloader;
import zing.downloader.utils.Constant;
import zing.downloader.utils.DirectoryUtil;

import java.util.List;

public class ZingDownloader implements IZingDownloader {

    private IDownloadExecutor downloadExecutor = new DownloadExecutor();

    private IHtmlController htmlUtil = new HtmlController();

    @Override
    public void downloadFromPlayerListing(String url) {
        Element bodyElement = htmlUtil.getBodyElement(url);

        Element artistElement = htmlUtil.getElementByClassName(bodyElement, "div h1", "detail-title");

        String artistName = artistElement.tagName("a").text();
        DirectoryUtil.setDirectory(artistName);

        List<Element> songListElements = htmlUtil.getElementsByClassName(bodyElement, Constant.HTML_UL_TAG, Constant.PLAY_LIST_CLASS_NAME);
        if (songListElements == null || songListElements.size() == 0) {
            songListElements = htmlUtil.getElementsByClassName(bodyElement, Constant.HTML_DIV_TAG, Constant.PLAY_LIST_CLASS_NAME);
        }

        List<Song> songs = htmlUtil.getListSongFromPlayerListing(songListElements.get(0));
        downloadExecutor.downloadListOfSong(songs);
    }

    @Override
    public void downloadFromArtistListing(String url) {
        Element bodyElement = htmlUtil.getBodyElement(url);

        Element artistElement = htmlUtil.getElementByClassName(bodyElement, "div h5", "detail-title");

        String artistName = artistElement.tagName("a").text();
        DirectoryUtil.setDirectory(artistName);

        List<Element> songListElements = htmlUtil.getElementsByClassName(bodyElement, Constant.HTML_UL_TAG, Constant.SONG_LIST_CLASS_NAME);
        if (songListElements == null || songListElements.size() == 0) {
            songListElements = htmlUtil.getElementsByClassName(bodyElement, Constant.HTML_DIV_TAG, Constant.SONG_LIST_CLASS_NAME);
        }

        List<Song> songs = htmlUtil.getListSongFromArtistListing(songListElements.get(0));
        downloadExecutor.downloadListOfSong(songs);
    }

    @Override
    public void downloadFromHotMusic(String url) {
        Element bodyElement = htmlUtil.getBodyElement(url);

        String hotMusicName = htmlUtil.getElementByClassName(bodyElement, "div h1", "new-content-block-title").text();
        DirectoryUtil.setDirectory(hotMusicName);

        List<Element> songListElements = htmlUtil.getElementsByClassName(bodyElement, Constant.HTML_DIV_TAG, "detail-content hotmusic bxh-detail");

        List<Song> songs = htmlUtil.getListSongFromHotMusic(songListElements.get(0));
        downloadExecutor.downloadListOfSong(songs);
    }

}
